home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python151_Src.lha / Python1.5_Source / Objects / stringobject.c < prev    next >
C/C++ Source or Header  |  1998-05-30  |  24KB  |  1,117 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* String object implementation */
  33.  
  34. #include "Python.h"
  35.  
  36. #include "mymath.h"
  37. #include <ctype.h>
  38.  
  39. #include "protos/stringobject_protos.h"
  40.  
  41. #ifdef COUNT_ALLOCS
  42. int null_strings, one_strings;
  43. #endif
  44.  
  45. #ifdef HAVE_LIMITS_H
  46. #include <limits.h>
  47. #else
  48. #ifndef UCHAR_MAX
  49. #define UCHAR_MAX 255
  50. #endif
  51. #endif
  52.  
  53. static PyStringObject *characters[UCHAR_MAX + 1];
  54. #ifndef DONT_SHARE_SHORT_STRINGS
  55. static PyStringObject *nullstring;
  56. #endif
  57.  
  58. /*
  59.    Newsizedstringobject() and newstringobject() try in certain cases
  60.    to share string objects.  When the size of the string is zero,
  61.    these routines always return a pointer to the same string object;
  62.    when the size is one, they return a pointer to an already existing
  63.    object if the contents of the string is known.  For
  64.    newstringobject() this is always the case, for
  65.    newsizedstringobject() this is the case when the first argument in
  66.    not NULL.
  67.    A common practice to allocate a string and then fill it in or
  68.    change it must be done carefully.  It is only allowed to change the
  69.    contents of the string if the obect was gotten from
  70.    newsizedstringobject() with a NULL first argument, because in the
  71.    future these routines may try to do even more sharing of objects.
  72. */
  73. PyObject *
  74. PyString_FromStringAndSize(str, size)
  75.     const char *str;
  76.     int size;
  77. {
  78.     register PyStringObject *op;
  79. #ifndef DONT_SHARE_SHORT_STRINGS
  80.     if (size == 0 && (op = nullstring) != NULL) {
  81. #ifdef COUNT_ALLOCS
  82.         null_strings++;
  83. #endif
  84.         Py_INCREF(op);
  85.         return (PyObject *)op;
  86.     }
  87.     if (size == 1 && str != NULL &&
  88.         (op = characters[*str & UCHAR_MAX]) != NULL)
  89.     {
  90. #ifdef COUNT_ALLOCS
  91.         one_strings++;
  92. #endif
  93.         Py_INCREF(op);
  94.         return (PyObject *)op;
  95.     }
  96. #endif /* DONT_SHARE_SHORT_STRINGS */
  97.     op = (PyStringObject *)
  98.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  99.     if (op == NULL)
  100.         return PyErr_NoMemory();
  101.     op->ob_type = &PyString_Type;
  102.     op->ob_size = size;
  103. #ifdef CACHE_HASH
  104.     op->ob_shash = -1;
  105. #endif
  106. #ifdef INTERN_STRINGS
  107.     op->ob_sinterned = NULL;
  108. #endif
  109.     _Py_NewReference(op);
  110.     if (str != NULL)
  111.         memcpy(op->ob_sval, str, size);
  112.     op->ob_sval[size] = '\0';
  113. #ifndef DONT_SHARE_SHORT_STRINGS
  114.     if (size == 0) {
  115.         nullstring = op;
  116.         Py_INCREF(op);
  117.     } else if (size == 1 && str != NULL) {
  118.         characters[*str & UCHAR_MAX] = op;
  119.         Py_INCREF(op);
  120.     }
  121. #endif
  122.     return (PyObject *) op;
  123. }
  124.  
  125. PyObject *
  126. PyString_FromString(str)
  127.     const char *str;
  128. {
  129.     register unsigned int size = strlen(str);
  130.     register PyStringObject *op;
  131. #ifndef DONT_SHARE_SHORT_STRINGS
  132.     if (size == 0 && (op = nullstring) != NULL) {
  133. #ifdef COUNT_ALLOCS
  134.         null_strings++;
  135. #endif
  136.         Py_INCREF(op);
  137.         return (PyObject *)op;
  138.     }
  139.     if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  140. #ifdef COUNT_ALLOCS
  141.         one_strings++;
  142. #endif
  143.         Py_INCREF(op);
  144.         return (PyObject *)op;
  145.     }
  146. #endif /* DONT_SHARE_SHORT_STRINGS */
  147.     op = (PyStringObject *)
  148.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  149.     if (op == NULL)
  150.         return PyErr_NoMemory();
  151.     op->ob_type = &PyString_Type;
  152.     op->ob_size = size;
  153. #ifdef CACHE_HASH
  154.     op->ob_shash = -1;
  155. #endif
  156. #ifdef INTERN_STRINGS
  157.     op->ob_sinterned = NULL;
  158. #endif
  159.     _Py_NewReference(op);
  160.     strcpy(op->ob_sval, str);
  161. #ifndef DONT_SHARE_SHORT_STRINGS
  162.     if (size == 0) {
  163.         nullstring = op;
  164.         Py_INCREF(op);
  165.     } else if (size == 1) {
  166.         characters[*str & UCHAR_MAX] = op;
  167.         Py_INCREF(op);
  168.     }
  169. #endif
  170.     return (PyObject *) op;
  171. }
  172.  
  173. static void
  174. string_dealloc(op)
  175.     PyObject *op;
  176. {
  177.     PyMem_DEL(op);
  178. }
  179.  
  180. int
  181. PyString_Size(op)
  182.     register PyObject *op;
  183. {
  184.     if (!PyString_Check(op)) {
  185.         PyErr_BadInternalCall();
  186.         return -1;
  187.     }
  188.     return ((PyStringObject *)op) -> ob_size;
  189. }
  190.  
  191. /*const*/ char *
  192. PyString_AsString(op)
  193.     register PyObject *op;
  194. {
  195.     if (!PyString_Check(op)) {
  196.         PyErr_BadInternalCall();
  197.         return NULL;
  198.     }
  199.     return ((PyStringObject *)op) -> ob_sval;
  200. }
  201.  
  202. /* Methods */
  203.  
  204. static int
  205. string_print(op, fp, flags)
  206.     PyStringObject *op;
  207.     FILE *fp;
  208.     int flags;
  209. {
  210.     int i;
  211.     char c;
  212.     int quote;
  213.     /* XXX Ought to check for interrupts when writing long strings */
  214.     if (flags & Py_PRINT_RAW) {
  215.         fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
  216.         return 0;
  217.     }
  218.  
  219.     /* figure out which quote to use; single is prefered */
  220.     quote = '\'';
  221.     if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  222.         quote = '"';
  223.  
  224.     fputc(quote, fp);
  225.     for (i = 0; i < op->ob_size; i++) {
  226.         c = op->ob_sval[i];
  227.         if (c == quote || c == '\\')
  228.             fprintf(fp, "\\%c", c);
  229.         else if (c < ' ' || c >= 0177)
  230.             fprintf(fp, "\\%03o", c & 0377);
  231.         else
  232.             fputc(c, fp);
  233.     }
  234.     fputc(quote, fp);
  235.     return 0;
  236. }
  237.  
  238. static PyObject *
  239. string_repr(op)
  240.     register PyStringObject *op;
  241. {
  242.     /* XXX overflow? */
  243.     int newsize = 2 + 4 * op->ob_size * sizeof(char);
  244.     PyObject *v = PyString_FromStringAndSize((char *)NULL, newsize);
  245.     if (v == NULL) {
  246.         return NULL;
  247.     }
  248.     else {
  249.         register int i;
  250.         register char c;
  251.         register char *p;
  252.         int quote;
  253.  
  254.         /* figure out which quote to use; single is prefered */
  255.         quote = '\'';
  256.         if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  257.             quote = '"';
  258.  
  259.         p = ((PyStringObject *)v)->ob_sval;
  260.         *p++ = quote;
  261.         for (i = 0; i < op->ob_size; i++) {
  262.             c = op->ob_sval[i];
  263.             if (c == quote || c == '\\')
  264.                 *p++ = '\\', *p++ = c;
  265.             else if (c < ' ' || c >= 0177) {
  266.                 sprintf(p, "\\%03o", c & 0377);
  267.                 while (*p != '\0')
  268.                     p++;
  269.             }
  270.             else
  271.                 *p++ = c;
  272.         }
  273.         *p++ = quote;
  274.         *p = '\0';
  275.         _PyString_Resize(
  276.             &v, (int) (p - ((PyStringObject *)v)->ob_sval));
  277.         return v;
  278.     }
  279. }
  280.  
  281. static int
  282. string_length(a)
  283.     PyStringObject *a;
  284. {
  285.     return a->ob_size;
  286. }
  287.  
  288. static PyObject *
  289. string_concat(a, bb)
  290.     register PyStringObject *a;
  291.     register PyObject *bb;
  292. {
  293.     register unsigned int size;
  294.     register PyStringObject *op;
  295.     if (!PyString_Check(bb)) {
  296.         PyErr_BadArgument();
  297.         return NULL;
  298.     }
  299. #define b ((PyStringObject *)bb)
  300.     /* Optimize cases with empty left or right operand */
  301.     if (a->ob_size == 0) {
  302.         Py_INCREF(bb);
  303.         return bb;
  304.     }
  305.     if (b->ob_size == 0) {
  306.         Py_INCREF(a);
  307.         return (PyObject *)a;
  308.     }
  309.     size = a->ob_size + b->ob_size;
  310.     op = (PyStringObject *)
  311.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  312.     if (op == NULL)
  313.         return PyErr_NoMemory();
  314.     op->ob_type = &PyString_Type;
  315.     op->ob_size = size;
  316. #ifdef CACHE_HASH
  317.     op->ob_shash = -1;
  318. #endif
  319. #ifdef INTERN_STRINGS
  320.     op->ob_sinterned = NULL;
  321. #endif
  322.     _Py_NewReference(op);
  323.     memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size);
  324.     memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size);
  325.     op->ob_sval[size] = '\0';
  326.     return (PyObject *) op;
  327. #undef b
  328. }
  329.  
  330. static PyObject *
  331. string_repeat(a, n)
  332.     register PyStringObject *a;
  333.     register int n;
  334. {
  335.     register int i;
  336.     register int size;
  337.     register PyStringObject *op;
  338.     if (n < 0)
  339.         n = 0;
  340.     size = a->ob_size * n;
  341.     if (size == a->ob_size) {
  342.         Py_INCREF(a);
  343.         return (PyObject *)a;
  344.     }
  345.     op = (PyStringObject *)
  346.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  347.     if (op == NULL)
  348.         return PyErr_NoMemory();
  349.     op->ob_type = &PyString_Type;
  350.     op->ob_size = size;
  351. #ifdef CACHE_HASH
  352.     op->ob_shash = -1;
  353. #endif
  354. #ifdef INTERN_STRINGS
  355.     op->ob_sinterned = NULL;
  356. #endif
  357.     _Py_NewReference(op);
  358.     for (i = 0; i < size; i += a->ob_size)
  359.         memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size);
  360.     op->ob_sval[size] = '\0';
  361.     return (PyObject *) op;
  362. }
  363.  
  364. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  365.  
  366. static PyObject *
  367. string_slice(a, i, j)
  368.     register PyStringObject *a;
  369.     register int i, j; /* May be negative! */
  370. {
  371.     if (i < 0)
  372.         i = 0;
  373.     if (j < 0)
  374.         j = 0; /* Avoid signed/unsigned bug in next line */
  375.     if (j > a->ob_size)
  376.         j = a->ob_size;
  377.     if (i == 0 && j == a->ob_size) { /* It's the same as a */
  378.         Py_INCREF(a);
  379.         return (PyObject *)a;
  380.     }
  381.     if (j < i)
  382.         j = i;
  383.     return PyString_FromStringAndSize(a->ob_sval + i, (int) (j-i));
  384. }
  385.  
  386. static PyObject *
  387. string_item(a, i)
  388.     PyStringObject *a;
  389.     register int i;
  390. {
  391.     int c;
  392.     PyObject *v;
  393.     if (i < 0 || i >= a->ob_size) {
  394.         PyErr_SetString(PyExc_IndexError, "string index out of range");
  395.         return NULL;
  396.     }
  397.     c = a->ob_sval[i] & UCHAR_MAX;
  398.     v = (PyObject *) characters[c];
  399. #ifdef COUNT_ALLOCS
  400.     if (v != NULL)
  401.         one_strings++;
  402. #endif
  403.     if (v == NULL) {
  404.         v = PyString_FromStringAndSize((char *)NULL, 1);
  405.         if (v == NULL)
  406.             return NULL;
  407.         characters[c] = (PyStringObject *) v;
  408.         ((PyStringObject *)v)->ob_sval[0] = c;
  409.     }
  410.     Py_INCREF(v);
  411.     return v;
  412. }
  413.  
  414. static int
  415. string_compare(a, b)
  416.     PyStringObject *a, *b;
  417. {
  418.     int len_a = a->ob_size, len_b = b->ob_size;
  419.     int min_len = (len_a < len_b) ? len_a : len_b;
  420.     int cmp;
  421.     if (min_len > 0) {
  422.         cmp = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  423.         if (cmp == 0)
  424.             cmp = memcmp(a->ob_sval, b->ob_sval, min_len);
  425.         if (cmp != 0)
  426.             return cmp;
  427.     }
  428.     return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  429. }
  430.  
  431. static long
  432. string_hash(a)
  433.     PyStringObject *a;
  434. {
  435.     register int len;
  436.     register unsigned char *p;
  437.     register long x;
  438.  
  439. #ifdef CACHE_HASH
  440.     if (a->ob_shash != -1)
  441.         return a->ob_shash;
  442. #ifdef INTERN_STRINGS
  443.     if (a->ob_sinterned != NULL)
  444.         return (a->ob_shash =
  445.             ((PyStringObject *)(a->ob_sinterned))->ob_shash);
  446. #endif
  447. #endif
  448.     len = a->ob_size;
  449.     p = (unsigned char *) a->ob_sval;
  450.     x = *p << 7;
  451.     while (--len >= 0)
  452.         x = (1000003*x) ^ *p++;
  453.     x ^= a->ob_size;
  454.     if (x == -1)
  455.         x = -2;
  456. #ifdef CACHE_HASH
  457.     a->ob_shash = x;
  458. #endif
  459.     return x;
  460. }
  461.  
  462. static int
  463. string_buffer_getreadbuf(self, index, ptr)
  464.     PyStringObject *self;
  465.     int index;
  466.     const void **ptr;
  467. {
  468.     if ( index != 0 ) {
  469.         PyErr_SetString(PyExc_SystemError,
  470.                 "Accessing non-existent string segment");
  471.         return -1;
  472.     }
  473.     *ptr = (void *)self->ob_sval;
  474.     return self->ob_size;
  475. }
  476.  
  477. static int
  478. string_buffer_getwritebuf(self, index, ptr)
  479.     PyStringObject *self;
  480.     int index;
  481.     const void **ptr;
  482. {
  483.     PyErr_SetString(PyExc_TypeError,
  484.             "Cannot use string as modifyable buffer");
  485.     return -1;
  486. }
  487.  
  488. static int
  489. string_buffer_getsegcount(self, lenp)
  490.     PyStringObject *self;
  491.     int *lenp;
  492. {
  493.     if ( lenp )
  494.         *lenp = self->ob_size;
  495.     return 1;
  496. }
  497.  
  498. static PySequenceMethods string_as_sequence = {
  499.     (inquiry)string_length, /*sq_length*/
  500.     (binaryfunc)string_concat, /*sq_concat*/
  501.     (intargfunc)string_repeat, /*sq_repeat*/
  502.     (intargfunc)string_item, /*sq_item*/
  503.     (intintargfunc)string_slice, /*sq_slice*/
  504.     0,        /*sq_ass_item*/
  505.     0,        /*sq_ass_slice*/
  506. };
  507.  
  508. static PyBufferProcs string_as_buffer = {
  509.     (getreadbufferproc)string_buffer_getreadbuf,
  510.     (getwritebufferproc)string_buffer_getwritebuf,
  511.     (getsegcountproc)string_buffer_getsegcount,
  512. };
  513.  
  514. PyTypeObject PyString_Type = {
  515.     PyObject_HEAD_INIT(&PyType_Type)
  516.     0,
  517.     "string",
  518.     sizeof(PyStringObject),
  519.     sizeof(char),
  520.     (destructor)string_dealloc, /*tp_dealloc*/
  521.     (printfunc)string_print, /*tp_print*/
  522.     0,        /*tp_getattr*/
  523.     0,        /*tp_setattr*/
  524.     (cmpfunc)string_compare, /*tp_compare*/
  525.     (reprfunc)string_repr, /*tp_repr*/
  526.     0,        /*tp_as_number*/
  527.     &string_as_sequence,    /*tp_as_sequence*/
  528.     0,        /*tp_as_mapping*/
  529.     (hashfunc)string_hash, /*tp_hash*/
  530.     0,        /*tp_call*/
  531.     0,        /*tp_str*/
  532.     0,        /*tp_getattro*/
  533.     0,        /*tp_setattro*/
  534.     &string_as_buffer,    /*tp_as_buffer*/
  535.     0,        /*tp_xxx4*/
  536.     0,        /*tp_doc*/
  537. };
  538.  
  539. void
  540. PyString_Concat(pv, w)
  541.     register PyObject **pv;
  542.     register PyObject *w;
  543. {
  544.     register PyObject *v;
  545.     if (*pv == NULL)
  546.         return;
  547.     if (w == NULL || !PyString_Check(*pv)) {
  548.         Py_DECREF(*pv);
  549.         *pv = NULL;
  550.         return;
  551.     }
  552.     v = string_concat((PyStringObject *) *pv, w);
  553.     Py_DECREF(*pv);
  554.     *pv = v;
  555. }
  556.  
  557. void
  558. PyString_ConcatAndDel(pv, w)
  559.     register PyObject **pv;
  560.     register PyObject *w;
  561. {
  562.     PyString_Concat(pv, w);
  563.     Py_XDECREF(w);
  564. }
  565.  
  566.  
  567. /* The following function breaks the notion that strings are immutable:
  568.    it changes the size of a string.  We get away with this only if there
  569.    is only one module referencing the object.  You can also think of it
  570.    as creating a new string object and destroying the old one, only
  571.    more efficiently.  In any case, don't use this if the string may
  572.    already be known to some other part of the code... */
  573.  
  574. int
  575. _PyString_Resize(pv, newsize)
  576.     PyObject **pv;
  577.     int newsize;
  578. {
  579.     register PyObject *v;
  580.     register PyStringObject *sv;
  581.     v = *pv;
  582.     if (!PyString_Check(v) || v->ob_refcnt != 1) {
  583.         *pv = 0;
  584.         Py_DECREF(v);
  585.         PyErr_BadInternalCall();
  586.         return -1;
  587.     }
  588.     /* XXX UNREF/NEWREF interface should be more symmetrical */
  589. #ifdef Py_REF_DEBUG
  590.     --_Py_RefTotal;
  591. #endif
  592.     _Py_ForgetReference(v);
  593.     *pv = (PyObject *)
  594.         realloc((char *)v,
  595.             sizeof(PyStringObject) + newsize * sizeof(char));
  596.     if (*pv == NULL) {
  597.         PyMem_DEL(v);
  598.         PyErr_NoMemory();
  599.         return -1;
  600.     }
  601.     _Py_NewReference(*pv);
  602.     sv = (PyStringObject *) *pv;
  603.     sv->ob_size = newsize;
  604.     sv->ob_sval[newsize] = '\0';
  605.     return 0;
  606. }
  607.  
  608. /* Helpers for formatstring */
  609.  
  610. static PyObject *
  611. getnextarg(args, arglen, p_argidx)
  612.     PyObject *args;
  613.     int arglen;
  614.     int *p_argidx;
  615. {
  616.     int argidx = *p_argidx;
  617.     if (argidx < arglen) {
  618.         (*p_argidx)++;
  619.         if (arglen < 0)
  620.             return args;
  621.         else
  622.             return PyTuple_GetItem(args, argidx);
  623.     }
  624.     PyErr_SetString(PyExc_TypeError,
  625.             "not enough arguments for format string");
  626.     return NULL;
  627. }
  628.  
  629. #define F_LJUST (1<<0)
  630. #define F_SIGN    (1<<1)
  631. #define F_BLANK (1<<2)
  632. #define F_ALT    (1<<3)
  633. #define F_ZERO    (1<<4)
  634.  
  635. static int
  636. formatfloat(buf, flags, prec, type, v)
  637.     char *buf;
  638.     int flags;
  639.     int prec;
  640.     int type;
  641.     PyObject *v;
  642. {
  643.     char fmt[20];
  644.     double x;
  645.     if (!PyArg_Parse(v, "d;float argument required", &x))
  646.         return -1;
  647.     if (prec < 0)
  648.         prec = 6;
  649.     if (prec > 50)
  650.         prec = 50; /* Arbitrary limitation */
  651.     if (type == 'f' && fabs(x)/1e25 >= 1e25)
  652.         type = 'g';
  653.     sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type);
  654.     sprintf(buf, fmt, x);
  655.     return strlen(buf);
  656. }
  657.  
  658. static int
  659. formatint(buf, flags, prec, type, v)
  660.     char *buf;
  661.     int flags;
  662.     int prec;
  663.     int type;
  664.     PyObject *v;
  665. {
  666.     char fmt[20];
  667.     long x;
  668.     if (!PyArg_Parse(v, "l;int argument required", &x))
  669.         return -1;
  670.     if (prec < 0)
  671.         prec = 1;
  672.     sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type);
  673.     sprintf(buf, fmt, x);
  674.     return strlen(buf);
  675. }
  676.  
  677. static int
  678. formatchar(buf, v)
  679.     char *buf;
  680.     PyObject *v;
  681. {
  682.     if (PyString_Check(v)) {
  683.         if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
  684.             return -1;
  685.     }
  686.     else {
  687.         if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
  688.             return -1;
  689.     }
  690.     buf[1] = '\0';
  691.     return 1;
  692. }
  693.  
  694.  
  695. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
  696.  
  697. PyObject *
  698. PyString_Format(format, args)
  699.     PyObject *format;
  700.     PyObject *args;
  701. {
  702.     char *fmt, *res;
  703.     int fmtcnt, rescnt, reslen, arglen, argidx;
  704.     int args_owned = 0;
  705.     PyObject *result;
  706.     PyObject *dict = NULL;
  707.     if (format == NULL || !PyString_Check(format) || args == NULL) {
  708.         PyErr_BadInternalCall();
  709.         return NULL;
  710.     }
  711.     fmt = PyString_AsString(format);
  712.     fmtcnt = PyString_Size(format);
  713.     reslen = rescnt = fmtcnt + 100;
  714.     result = PyString_FromStringAndSize((char *)NULL, reslen);
  715.     if (result == NULL)
  716.         return NULL;
  717.     res = PyString_AsString(result);
  718.     if (PyTuple_Check(args)) {
  719.         arglen = PyTuple_Size(args);
  720.         argidx = 0;
  721.     }
  722.     else {
  723.         arglen = -1;
  724.         argidx = -2;
  725.     }
  726.     if (args->ob_type->tp_as_mapping)
  727.         dict = args;
  728.     while (--fmtcnt >= 0) {
  729.         if (*fmt != '%') {
  730.             if (--rescnt < 0) {
  731.                 rescnt = fmtcnt + 100;
  732.                 reslen += rescnt;
  733.                 if (_PyString_Resize(&result, reslen) < 0)
  734.                     return NULL;
  735.                 res = PyString_AsString(result)
  736.                     + reslen - rescnt;
  737.                 --rescnt;
  738.             }
  739.             *res++ = *fmt++;
  740.         }
  741.         else {
  742.             /* Got a format specifier */
  743.             int flags = 0;
  744.             int width = -1;
  745.             int prec = -1;
  746.             int size = 0;
  747.             int c = '\0';
  748.             int fill;
  749.             PyObject *v = NULL;
  750.             PyObject *temp = NULL;
  751.             char *buf;
  752.             int sign;
  753.             int len;
  754.             char tmpbuf[120]; /* For format{float,int,char}() */
  755.             fmt++;
  756.             if (*fmt == '(') {
  757.                 char *keystart;
  758.                 int keylen;
  759.                 PyObject *key;
  760.                 int pcount = 1;
  761.  
  762.                 if (dict == NULL) {
  763.                     PyErr_SetString(PyExc_TypeError,
  764.                          "format requires a mapping"); 
  765.                     goto error;
  766.                 }
  767.                 ++fmt;
  768.                 --fmtcnt;
  769.                 keystart = fmt;
  770.                 /* Skip over balanced parentheses */
  771.                 while (pcount > 0 && --fmtcnt >= 0) {
  772.                     if (*fmt == ')')
  773.                         --pcount;
  774.                     else if (*fmt == '(')
  775.                         ++pcount;
  776.                     fmt++;
  777.                 }
  778.                 keylen = fmt - keystart - 1;
  779.                 if (fmtcnt < 0 || pcount > 0) {
  780.                     PyErr_SetString(PyExc_ValueError,
  781.                            "incomplete format key");
  782.                     goto error;
  783.                 }
  784.                 key = PyString_FromStringAndSize(keystart,
  785.                                  keylen);
  786.                 if (key == NULL)
  787.                     goto error;
  788.                 if (args_owned) {
  789.                     Py_DECREF(args);
  790.                     args_owned = 0;
  791.                 }
  792.                 args = PyObject_GetItem(dict, key);
  793.                 Py_DECREF(key);
  794.                 if (args == NULL) {
  795.                     goto error;
  796.                 }
  797.                 args_owned = 1;
  798.                 arglen = -1;
  799.                 argidx = -2;
  800.             }
  801.             while (--fmtcnt >= 0) {
  802.                 switch (c = *fmt++) {
  803.                 case '-': flags |= F_LJUST; continue;
  804.                 case '+': flags |= F_SIGN; continue;
  805.                 case ' ': flags |= F_BLANK; continue;
  806.                 case '#': flags |= F_ALT; continue;
  807.                 case '0': flags |= F_ZERO; continue;
  808.                 }
  809.                 break;
  810.             }
  811.             if (c == '*') {
  812.                 v = getnextarg(args, arglen, &argidx);
  813.                 if (v == NULL)
  814.                     goto error;
  815.                 if (!PyInt_Check(v)) {
  816.                     PyErr_SetString(PyExc_TypeError,
  817.                             "* wants int");
  818.                     goto error;
  819.                 }
  820.                 width = PyInt_AsLong(v);
  821.                 if (width < 0)
  822.                     width = 0;
  823.                 if (--fmtcnt >= 0)
  824.                     c = *fmt++;
  825.             }
  826.             else if (c >= 0 && isdigit(c)) {
  827.                 width = c - '0';
  828.                 while (--fmtcnt >= 0) {
  829.                     c = Py_CHARMASK(*fmt++);
  830.                     if (!isdigit(c))
  831.                         break;
  832.                     if ((width*10) / 10 != width) {
  833.                         PyErr_SetString(
  834.                             PyExc_ValueError,
  835.                             "width too big");
  836.                         goto error;
  837.                     }
  838.                     width = width*10 + (c - '0');
  839.                 }
  840.             }
  841.             if (c == '.') {
  842.                 prec = 0;
  843.                 if (--fmtcnt >= 0)
  844.                     c = *fmt++;
  845.                 if (c == '*') {
  846.                     v = getnextarg(args, arglen, &argidx);
  847.                     if (v == NULL)
  848.                         goto error;
  849.                     if (!PyInt_Check(v)) {
  850.                         PyErr_SetString(
  851.                             PyExc_TypeError,
  852.                             "* wants int");
  853.                         goto error;
  854.                     }
  855.                     prec = PyInt_AsLong(v);
  856.                     if (prec < 0)
  857.                         prec = 0;
  858.                     if (--fmtcnt >= 0)
  859.                         c = *fmt++;
  860.                 }
  861.                 else if (c >= 0 && isdigit(c)) {
  862.                     prec = c - '0';
  863.                     while (--fmtcnt >= 0) {
  864.                         c = Py_CHARMASK(*fmt++);
  865.                         if (!isdigit(c))
  866.                             break;
  867.                         if ((prec*10) / 10 != prec) {
  868.                             PyErr_SetString(
  869.                                 PyExc_ValueError,
  870.                                 "prec too big");
  871.                             goto error;
  872.                         }
  873.                         prec = prec*10 + (c - '0');
  874.                     }
  875.                 }
  876.             } /* prec */
  877.             if (fmtcnt >= 0) {
  878.                 if (c == 'h' || c == 'l' || c == 'L') {
  879.                     size = c;
  880.                     if (--fmtcnt >= 0)
  881.                         c = *fmt++;
  882.                 }
  883.             }
  884.             if (fmtcnt < 0) {
  885.                 PyErr_SetString(PyExc_ValueError,
  886.                         "incomplete format");
  887.                 goto error;
  888.             }
  889.             if (c != '%') {
  890.                 v = getnextarg(args, arglen, &argidx);
  891.                 if (v == NULL)
  892.                     goto error;
  893.             }
  894.             sign = 0;
  895.             fill = ' ';
  896.             switch (c) {
  897.             case '%':
  898.                 buf = "%";
  899.                 len = 1;
  900.                 break;
  901.             case 's':
  902.                 temp = PyObject_Str(v);
  903.                 if (temp == NULL)
  904.                     goto error;
  905.                 buf = PyString_AsString(temp);
  906.                 len = PyString_Size(temp);
  907.                 if (prec >= 0 && len > prec)
  908.                     len = prec;
  909.                 break;
  910.             case 'i':
  911.             case 'd':
  912.             case 'u':
  913.             case 'o':
  914.             case 'x':
  915.             case 'X':
  916.                 if (c == 'i')
  917.                     c = 'd';
  918.                 buf = tmpbuf;
  919.                 len = formatint(buf, flags, prec, c, v);
  920.                 if (len < 0)
  921.                     goto error;
  922.                 sign = (c == 'd');
  923.                 if (flags&F_ZERO) {
  924.                     fill = '0';
  925.                     if ((flags&F_ALT) &&
  926.                         (c == 'x' || c == 'X') &&
  927.                         buf[0] == '0' && buf[1] == c) {
  928.                         *res++ = *buf++;
  929.                         *res++ = *buf++;
  930.                         rescnt -= 2;
  931.                         len -= 2;
  932.                         width -= 2;
  933.                         if (width < 0)
  934.                             width = 0;
  935.                     }
  936.                 }
  937.                 break;
  938.             case 'e':
  939.             case 'E':
  940.             case 'f':
  941.             case 'g':
  942.             case 'G':
  943.                 buf = tmpbuf;
  944.                 len = formatfloat(buf, flags, prec, c, v);
  945.                 if (len < 0)
  946.                     goto error;
  947.                 sign = 1;
  948.                 if (flags&F_ZERO)
  949.                     fill = '0';
  950.                 break;
  951.             case 'c':
  952.                 buf = tmpbuf;
  953.                 len = formatchar(buf, v);
  954.                 if (len < 0)
  955.                     goto error;
  956.                 break;
  957.             default:
  958.                 PyErr_Format(PyExc_ValueError,
  959.                 "unsupported format character '%c' (0x%x)",
  960.                     c, c);
  961.                 goto error;
  962.             }
  963.             if (sign) {
  964.                 if (*buf == '-' || *buf == '+') {
  965.                     sign = *buf++;
  966.                     len--;
  967.                 }
  968.                 else if (flags & F_SIGN)
  969.                     sign = '+';
  970.                 else if (flags & F_BLANK)
  971.                     sign = ' ';
  972.                 else
  973.                     sign = '\0';
  974.             }
  975.             if (width < len)
  976.                 width = len;
  977.             if (rescnt < width + (sign != '\0')) {
  978.                 reslen -= rescnt;
  979.                 rescnt = width + fmtcnt + 100;
  980.                 reslen += rescnt;
  981.                 if (_PyString_Resize(&result, reslen) < 0)
  982.                     return NULL;
  983.                 res = PyString_AsString(result)
  984.                     + reslen - rescnt;
  985.             }
  986.             if (sign) {
  987.                 if (fill != ' ')
  988.                     *res++ = sign;
  989.                 rescnt--;
  990.                 if (width > len)
  991.                     width--;
  992.             }
  993.             if (width > len && !(flags&F_LJUST)) {
  994.                 do {
  995.                     --rescnt;
  996.                     *res++ = fill;
  997.                 } while (--width > len);
  998.             }
  999.             if (sign && fill == ' ')
  1000.                 *res++ = sign;
  1001.             memcpy(res, buf, len);
  1002.             res += len;
  1003.             rescnt -= len;
  1004.             while (--width >= len) {
  1005.                 --rescnt;
  1006.                 *res++ = ' ';
  1007.             }
  1008.                         if (dict && (argidx < arglen) && c != '%') {
  1009.                                 PyErr_SetString(PyExc_TypeError,
  1010.                                            "not all arguments converted");
  1011.                                 goto error;
  1012.                         }
  1013.             Py_XDECREF(temp);
  1014.         } /* '%' */
  1015.     } /* until end */
  1016.     if (argidx < arglen && !dict) {
  1017.         PyErr_SetString(PyExc_TypeError,
  1018.                 "not all arguments converted");
  1019.         goto error;
  1020.     }
  1021.     if (args_owned) {
  1022.         Py_DECREF(args);
  1023.     }
  1024.     _PyString_Resize(&result, reslen - rescnt);
  1025.     return result;
  1026.  error:
  1027.     Py_DECREF(result);
  1028.     if (args_owned) {
  1029.         Py_DECREF(args);
  1030.     }
  1031.     return NULL;
  1032. }
  1033.  
  1034.  
  1035. #ifdef INTERN_STRINGS
  1036.  
  1037. static PyObject *interned;
  1038.  
  1039. void
  1040. PyString_InternInPlace(p)
  1041.     PyObject **p;
  1042. {
  1043.     register PyStringObject *s = (PyStringObject *)(*p);
  1044.     PyObject *t;
  1045.     if (s == NULL || !PyString_Check(s))
  1046.         Py_FatalError("PyString_InternInPlace: strings only please!");
  1047.     if ((t = s->ob_sinterned) != NULL) {
  1048.         if (t == (PyObject *)s)
  1049.             return;
  1050.         Py_INCREF(t);
  1051.         *p = t;
  1052.         Py_DECREF(s);
  1053.         return;
  1054.     }
  1055.     if (interned == NULL) {
  1056.         interned = PyDict_New();
  1057.         if (interned == NULL)
  1058.             return;
  1059.     }
  1060.     if ((t = PyDict_GetItem(interned, (PyObject *)s)) != NULL) {
  1061.         Py_INCREF(t);
  1062.         *p = s->ob_sinterned = t;
  1063.         Py_DECREF(s);
  1064.         return;
  1065.     }
  1066.     t = (PyObject *)s;
  1067.     if (PyDict_SetItem(interned, t, t) == 0) {
  1068.         s->ob_sinterned = t;
  1069.         return;
  1070.     }
  1071.     PyErr_Clear();
  1072. }
  1073.  
  1074.  
  1075. PyObject *
  1076. PyString_InternFromString(cp)
  1077.     const char *cp;
  1078. {
  1079.     PyObject *s = PyString_FromString(cp);
  1080.     if (s == NULL)
  1081.         return NULL;
  1082.     PyString_InternInPlace(&s);
  1083.     return s;
  1084. }
  1085.  
  1086. #endif
  1087.  
  1088. void
  1089. PyString_Fini()
  1090. {
  1091.     int i;
  1092.     for (i = 0; i < UCHAR_MAX + 1; i++) {
  1093.         Py_XDECREF(characters[i]);
  1094.         characters[i] = NULL;
  1095.     }
  1096. #ifndef DONT_SHARE_SHORT_STRINGS
  1097.     Py_XDECREF(nullstring);
  1098.     nullstring = NULL;
  1099. #endif
  1100. #ifdef INTERN_STRINGS
  1101.     if (interned) {
  1102.         int pos, changed;
  1103.         PyObject *key, *value;
  1104.         do {
  1105.             changed = 0;
  1106.             pos = 0;
  1107.             while (PyDict_Next(interned, &pos, &key, &value)) {
  1108.                 if (key->ob_refcnt == 2 && key == value) {
  1109.                     PyDict_DelItem(interned, key);
  1110.                     changed = 1;
  1111.                 }
  1112.             }
  1113.         } while (changed);
  1114.     }
  1115. #endif
  1116. }
  1117.